package com.zmn.oms.third.baidu_dtw.service.impl;

import com.alibaba.fastjson.JSON;
import com.zmn.base.common.data.common.dro.area.AreaDRO;
import com.zmn.base.common.data.dubbo.interfaces.area.AreaListRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.business.interfaces.baidumap.BaiduMapBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.model.bo.order.OrderBO;
import com.zmn.oms.model.dto.baidumap.LngLatLocation;
import com.zmn.oms.model.dto.order.create.CreateOrderFailMessage;
import com.zmn.oms.model.dto.order.proxy.CreateOrderDTO;
import com.zmn.oms.model.dto.product.ChannelProductMapDTO;
import com.zmn.oms.model.dto.product.OrderProductDTO;
import com.zmn.oms.model.entity.trace.BaiduOrderTrace;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.order.OrderChangeService;
import com.zmn.oms.services.interfaces.trace.ChannelOrderTraceService;
import com.zmn.oms.third.baidu_dtw.BaiduDtwConsts;
import com.zmn.oms.third.baidu_dtw.dto.BaiduDtwMessage;
import com.zmn.oms.third.baidu_dtw.service.BaiduDtwService;
import com.zmn.oms.third.base.util.ThirdOrderUtil;
import com.zmn.oms.zmn.business.interfaces.discount.ChannelDiscountService;
import com.zmn.oms.zmn.business.interfaces.product.ProductMappingBService;
import com.zmn.oms.zmn.business.interfaces.proxy.ProxyOrderBService;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.WorkFlowContextBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 类描述：
 *
 * @author lhl
 * @date 2020/01/16 20:55
 */
@Slf4j
@Service("baiduDtwService")
@SuppressWarnings("all")
public class BaiduDtwServiceImpl implements BaiduDtwService {

    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    protected AreaListRemoteService areaListRemoteService;

    @Autowired
    private ProxyOrderBService proxyOrderBService;
    @Autowired
    private WorkFlowContextBService workFlowContextBService;
    @Autowired
    private OrderChangeService orderChangeService;
    @Autowired
    private BaiduMapBService baiduMapBService;
    @Autowired
    private ChannelDiscountService channelDiscountService;
    @Autowired
    private ProductMappingBService productMappingBService;
    @Autowired
    private ChannelOrderTraceService channelOrderTraceService;

    @Override
    public void procMsg(String baiduMsg, Integer channelId) {

        try {
            BaiduDtwMessage baiduDtwMessage = JSON.parseObject(baiduMsg, BaiduDtwMessage.class);

            CreateOrderDTO createOrderDTO = buildOrderDTO(baiduDtwMessage, channelId);

            // 线索中：电话、地址、产品信息都有，保存订单
            if (ThirdOrderUtil.isOrderInfoIntact(createOrderDTO)) {
                OrderWork orderWork = saveNewOrder(createOrderDTO);

                // 保存订单渠道溯源数据
                BaiduOrderTrace baiduOrderTrace = BeanMapper.map(baiduDtwMessage,BaiduOrderTrace.class);
                baiduOrderTrace.setOrderId(orderWork.getOrderId());
                baiduOrderTrace.setChannelId(channelId);
                channelOrderTraceService.addBaiduOrderTrace(baiduOrderTrace);
            }
            // 当线索数据中缺少以下任意条件：电话、地址、产品
            // 将线索转到呼叫中心去
            else {
                CreateOrderFailMessage createOrderFailMessage = new CreateOrderFailMessage();
                createOrderFailMessage.setChannelId(createOrderDTO.getChannelId());
                createOrderFailMessage.setTelephone(createOrderDTO.getTelephone());
                createOrderFailMessage.setContactName(createOrderDTO.getContactName());
                createOrderFailMessage.setAddress(createOrderDTO.getAddressClues());
                createOrderFailMessage.setProductName(createOrderDTO.getProductClues());
                createOrderFailMessage.setCityId(createOrderDTO.getCityId());
                createOrderFailMessage.setExtData(baiduMsg);

                log.info("[{}] 信息不全，推送至呼叫中心 CreateOrderFailMessage=[{}]", BaiduDtwConsts.NAME,
                        JSON.toJSONString(createOrderFailMessage));
                orderChangeService.orderCreateFailSyncToApi(createOrderFailMessage);
            }
        } catch (Exception e) {
            log.info("【{}-消息-订单】消息处理失败！ErrorMsg:[{}]", BaiduDtwConsts.NAME, e.getMessage());
            log.error(e.getMessage(), e);
        }
       }

    private OrderWork saveNewOrder(CreateOrderDTO createOrderDTO) throws Exception {
        OrderBO orderBO = proxyOrderBService.createOrder(createOrderDTO);
        OrderWork orderWork = orderBO.getOrderWork();

        log.info("【{}-消息-订单】保存订单成功 OrderId:[{}]", BaiduDtwConsts.NAME, orderWork.getOrderId());

        try {
            // 工单自动流转
            workFlowContextBService.asyncAutoFlow(orderWork.getOrderId(),orderWork.getWorkId());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return orderWork;
    }

    /**
     * 创建录单对象
     * @param baiduDtwMessage
     * @return
     */
    private CreateOrderDTO buildOrderDTO(BaiduDtwMessage baiduDtwMessage, Integer channelId) throws Exception {

        if (CollectionUtil.isNullOrEmpty(baiduDtwMessage.getData())) {
            throw new Exception("数据为空");
        }

        CreateOrderDTO createOrderDTO = new CreateOrderDTO();
        createOrderDTO.setChannelId(channelId);

        List<BaiduDtwMessage.KeyValuePairs> unknowKeyValuePairs = new LinkedList<>();
        boolean isFillAddress = false;
        boolean isFillProductInfo = false;
        for (BaiduDtwMessage.KeyValuePairs item : baiduDtwMessage.getData()) {
            String itemName = item.getName();
            String itemType = item.getType();
            if (BaiduDtwConsts.KEY_NAME.equals(itemName) || BaiduDtwConsts.TYPE_NAME.equals(itemType)) {
                createOrderDTO.setContactName(item.getValue());
            }
            else if (BaiduDtwConsts.KEY_PHONE.equals(itemName) || BaiduDtwConsts.TYPE_PHONE.equals(itemType)) {
                createOrderDTO.setTelephone(item.getValue());
            }
            else if (BaiduDtwConsts.KEY_CITY.equals(itemName) || BaiduDtwConsts.TYPE_CITY.equals(itemType)) {
                _fillAddress(createOrderDTO, item.getValue());
                isFillAddress = true;
            }
            else if (BaiduDtwConsts.KEY_PRODUCT.equals(itemName) || BaiduDtwConsts.TYPE_PRODUCT.equals(itemType)) {
                _fillProductInfo(createOrderDTO, item.getValue(), channelId);
                isFillProductInfo = true;
            }
            else if (BaiduDtwConsts.KEY_DUTYTIME.equals(itemName) || BaiduDtwConsts.TYPE_DUTYTIME.equals(itemType)) {
                _fillDutyTime(createOrderDTO, item.getValue());
            }
            else {
                unknowKeyValuePairs.add(item);
            }
        }

        // 补充识别
        for (BaiduDtwMessage.KeyValuePairs item : unknowKeyValuePairs) {
            String itemName = Optional.ofNullable(item.getName()).orElse("");

            if (!isFillAddress) {
                if (itemName.contains("地址")) {
                    _fillAddress(createOrderDTO, item.getValue());
                    isFillAddress = true;
                    continue;
                }
            }

            if (!isFillProductInfo) {
                if (itemName.contains("服务") || itemName.contains("品类")) {
                    _fillProductInfo(createOrderDTO, item.getValue(), channelId);
                    isFillProductInfo = true;
                }
            }
        }

        createOrderDTO.setPlat(GlobalConsts.PLAT_MARK_ZMN);
        createOrderDTO.setGender(GlobalDict.GENDER_NO);
        createOrderDTO.setDisableDiscard(GlobalConsts.NO);
        createOrderDTO.setOperator("系统");
        createOrderDTO.setOperatorId((long) GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
        createOrderDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_CHANNEL);
        createOrderDTO.setInputType(OrderConsts.ORDER_INPUT_TYPE_API);

        // 优惠 - 2021/6/1 至 2021/9/1 优惠5元
        channelDiscountService.tbsTempDiscountFiveYuan(createOrderDTO);

        return createOrderDTO;
    }

    /**
     * 补全产品信息
     * @param zmnOrder
     * @param productStr
     */
    private void _fillProductInfo(CreateOrderDTO zmnOrder, String productStr, Integer channelId) {
        zmnOrder.setRemark(productStr);
        zmnOrder.setProductClues(productStr);

        // productStr格式：家电维修,空调,定频挂机空调维修（2-3P）
        OrderProductDTO orderProduct = new OrderProductDTO();

        do {
            if (StringUtil.isBlank(productStr)) {
                orderProduct.setProductId(OrderConsts.CHANNEL_DISABLED_PRODUCT_ID);
                break;
            }

            // 先通过接口查询渠道产品映射
            int idx = productStr.lastIndexOf(',');
            String productName = (idx >= 0 && idx < (productStr.length()-1)) ? productStr.substring(idx+1) : productStr;
            List<ChannelProductMapDTO> channelProductMapDTOList = productMappingBService.listChannelProductMapping(channelId,productName,null);
            if (CollectionUtil.isNotNullOrEmpty(channelProductMapDTOList)) {
                if (Objects.equals(channelProductMapDTOList.get(0).getShowType(), GlobalConsts.YES)) {
                    orderProduct.setShowProductId(channelProductMapDTOList.get(0).getProductId());
                    orderProduct.setProductShowType(GlobalConsts.YES);
                } else {
                    orderProduct.setProductId(channelProductMapDTOList.get(0).getProductId());
                }
                break;
            }

            // 优先使用前台产品
            /*Integer showProductId = BaiduDtwMapper.getShowProductId(productStr);
            if (showProductId != null) {
                orderProduct.setShowProductId(showProductId);
                orderProduct.setProductShowType(GlobalConsts.YES);
                break;
            }*/

            // 设置为其他
            orderProduct.setProductId(OrderConsts.CHANNEL_DISABLED_PRODUCT_ID);
        } while (false);

        orderProduct.setNumber(1);

        List<OrderProductDTO> list = new LinkedList<>();
        list.add(orderProduct);
        zmnOrder.setOrderProductList(list);

        zmnOrder.setOperatorLogRemark(zmnOrder.getOperatorLogRemark() +"；产品："+ productStr);
    }

    // 补全订单地址：将地址转换成符合我们自己系统使用的地址信息
    private void _fillAddress(CreateOrderDTO orderDTO, String addressStr) {
        // addressStr格式：北京 北京 啄木鸟北京技术部测试下单（测试数据）
        // 去掉空格和括号
        Pattern pattern = Pattern.compile("\\s+|（.*）|[(](.*)[)]");
        Matcher matcher = pattern.matcher(addressStr);
        String buyerAddress = matcher.replaceAll("");

        // 具体地址放入address
        orderDTO.setAddress(buyerAddress);
        orderDTO.setStreet(""); // street字段在数据库中不能为空

        LngLatLocation location = baiduMapBService.location(buyerAddress);
        if (location != null) {
            Double lng = Double.valueOf(location.getLng());
            Double lat = Double.valueOf(location.getLat());

            try {
                ResponseDTO<com.zmn.base.common.data.common.dro.area.AreaDRO> areaResponse = areaListRemoteService.getAreaByLatAndLng(lng, lat);

                AreaDRO areaDRO = areaResponse.getData();
                if (areaDRO != null) {
                    orderDTO.setCityId(areaDRO.getParentId());

                    orderDTO.setLatitude(lat);
                    orderDTO.setLongitude(lng);
                }
            } catch (Exception e) {
                log.error("【{}-消息-订单】使用经纬度获取CityId失败:[{}]", BaiduDtwConsts.NAME, e.getMessage(), e);
            }
        }

        // 记录一下完整地址
        orderDTO.setOperatorLogRemark(orderDTO.getOperatorLogRemark() + addressStr);
        // 记录线索中的完整地址信息，方便推送给呼叫中心
        orderDTO.setAddressClues(addressStr);
    }

    /**
     * 预约时间
     * @param orderDTO
     * @param dutyTimeStr
     */
    private void _fillDutyTime(CreateOrderDTO orderDTO, String dutyDateStr) {
        Date currTime = new Date();
        Date dutyTime = null;

        if (StringUtils.isNotBlank(dutyDateStr)) {
            Date dutyDate = DateUtil.parse(dutyDateStr, DateUtil.FORMAT_DATE);
            Date currDate = DateUtil.parse(DateUtil.toString(new Date(), DateUtil.FORMAT_DATE), DateUtil.FORMAT_DATE);
            if (dutyDate.getTime() > currDate.getTime()) {
                // 预约日期大于今天，设置为预约日期的上午10点
                dutyTime = DateUtil.parse(String.format("%s 10:00:00", dutyDateStr));
            }
        }

        if (dutyTime == null) {
            dutyTime = ThirdOrderUtil.getDefaultDutyTime();
        }

        orderDTO.setDutyTime(dutyTime);
    }
}
